<?php

namespace App\Common\Service;

// use think\facade\Http;
use think\facade\Cache;
use think\facade\DB;
use think\facade\Log;
use app\common\utils\Http;

class TokenService
{
    /**
     * @var string Token缓存key
     */
    const CACHE_KEY = 'w_py_token';
    
    /**
     * @var TokenService 单例实例
     */
    private static $instance = null;
    
    
    /**
     * 私有构造函数，防止外部实例化
     */
    // private function __construct()
    // {
    //     $this->initConfig();
    // }
    
    /**
     * 获取单例实例
     */
    public static function getInstance(): self
    {
        if (is_null(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    
    
    /**
     * 获取有效Token
     * 
     * @return string
     * @throws \Exception
     */
    public function getToken(): string
    {
        try {
            // 优先从缓存获取
            $token = Cache::get(self::CACHE_KEY);
            if ($token) {
                return $token;
            }

            // 从数据库获取未过期token
            $tokenInfo = DB::table('w_py_token')->where('id',1)->find();
            if ($tokenInfo['expires_at'] >time()) {
                // $this->setCache($tokenInfo->token);
                return $tokenInfo['token'];
            }else{
                // 重新获取token
                $postData= ['username' => $tokenInfo['username'], 'password' => $tokenInfo['password']];
                $response = Http::CURL('http://ai.zhuanfa.jijianjide.com:8800/api/user/login',$postData,'POST');
                $result = json_decode($response,true);
            
                if ($result['code'] !== 200) {
                    throw new \Exception('获取token失败：' . ($result['msg'] ?? '未知错误'));
                }
    
                $token = $result['token'];
                $now = time();
                $expiredAt = $now + 864000;
                
                // 保存到数据库
                DB::table('w_py_token')->where('id',1)->update([
                    'token' => $token,
                    'expires_at' => $expiredAt
                ]);
                return $token;
            }
            
            
        } catch (\Exception $e) {
            Log::error('获取Token失败: ' . $e->getMessage());
            throw $e;
        }
    }

    
    
    
    /**
     * 禁止克隆
     */
    private function __clone()
    {
    }
} 